var async = require('async');
var helpers = require('../../../helpers/alibaba');

module.exports = {
    title: 'Vulnerability Scan Enabled',
    category: 'Security Center',
    domain: 'Management and Governance',
    severity: 'Medium',
    description: 'Ensure that scheduled vulnerability scan is enabled on all servers.',
    more_info: 'Ensure that vulnerability scan is performed periodically to discover system vulnerabilities in time.',
    link: 'https://www.alibabacloud.com/help/en/security-center/user-guide/view-and-handle-vulnerabilities',
    recommended_action: 'Ensure scheduled vulnerability scan is enabled on all servers by applying all types of vulnerabilities with High and Medium scan levels enabled.',
    apis: ['TDS:DescribeVulConfig'],

    run: function(cache, settings, callback) {
        var results = [];
        var source = {};
        var regions = helpers.regions(settings);

        async.each(regions.tds, function(region, rcb) {
            var  describeVulConfig = helpers.addSource(cache, source,
                ['tds', 'DescribeVulConfig', region]);

            if (!describeVulConfig) {
                return rcb();
            }

            if ( describeVulConfig.err || ! describeVulConfig.data) {
                helpers.addResult(results, 3,
                    `Unable to query TDS vulnerability config: ${helpers.addError( describeVulConfig)}`,
                    region);
                return rcb();
            }

            if (!describeVulConfig.data.TargetConfigs) {
                helpers.addResult(results, 0, 'No TDS vulnerability config', region);
                return rcb();
            }
            
            var hasDisabledConfig = describeVulConfig.data.TargetConfigs.some(config => config.Config === 'off');

            if (hasDisabledConfig) {
                helpers.addResult(results, 2, 'Vulnerability scan is not enabled for all servers', region);
            } else {
                helpers.addResult(results, 0, 'Vulnerability scan is enabled for all servers', region);
            }

            rcb();
        }, function(){
            callback(null, results, source);
        });
    }
};
